import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/login/widgets/login_forget_input_decorator.dart';
import 'package:flutter_syt/domain/widgets/code_form_field.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/dyt_aliyun_widget.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '../../global_easy_loading.dart';

// forgetSetPasswordPage
@RoutePage(name: "forgetPasswordPage")
class ForgetPasswordPage extends StatefulWidget {
  // final int type;

  ///type  0 phone  1 email
  // const ForgetPasswordPage({required this.type});

  @override
  _ForgetPasswordPageState createState() => _ForgetPasswordPageState();
}

class _ForgetPasswordPageState extends State<ForgetPasswordPage> {
  final _formKey = GlobalKey<FormState>();

  // String phone = '';

  FocusNode phoneFocusNode = FocusNode();
  TextEditingController phoneController = TextEditingController();

  bool _canNext = false;
  FocusNode codeFocusNode = FocusNode();
  // TextEditingController codeController = TextEditingController();

  // PhoneWithAreaCodeEntity _phoneWithAreaCodeEntity = PhoneWithAreaCodeEntity();
  String _code = '';

  // String accountType = '';
  Future<bool> getSmsCode() async {
    final form = _formKey.currentState;

    if (form != null) {
      form.save();
      if (phoneController.text.length < 6 || phoneController.text.length > 60) {
        customShowToast(S.of(context).enter_valid_account);
        return false;
      }
      String type = '';
      try {
        type = await API.shared.login.postRegisterType(phoneController.text);
      } catch (e) {
        await UtilsOther.showCustomShowError(e);
        return true;
      }


      // if (type == '4' || type == '3') {
      //   customShowToast(S.of(context).login_unBind);
      //   return false;
      // }

      // phoneController

      // if (_phoneWithAreaCodeEntity.areaCode == '86') {
      //   if (!RegexUtil.isMobileSimple(_phoneWithAreaCodeEntity.phone)) {
      //     customShowToast(S.of(context).enter_valid_phone);
      //     return false;
      //   }
      // } else
      // if (!RegexUtil.matches(
      //     '^\\d{6,25}\$', _phoneWithAreaCodeEntity.phone)) {
      //   customShowToast(S.of(context).enter_valid_phone);
      //   return false;
      // }
      bool isVertifica = await UtilsOther.checkShowVertification(
          account: phoneController.text,
          context: context,
          status: DytAliyunStatus.DytAliyunStatusMessage);
      if (isVertifica == false) {
        return false;
      }
      try {
        // bool res = await API.shared.login.accountCode(phoneController.text);
        bool res = await (type == '2'
            ? API.shared.login
                .getEmailCode(phoneController.text, 'forgot-password')
            : API.shared.login.getPhoneCode(
                '',
                phoneController.text,
                // _phoneWithAreaCodeEntity.phone,

                'forgot-password'));
        customShowToast(S().send_code_3);
        // bool res = await API.shared.login.getPhoneCode(
        //     _phoneWithAreaCodeEntity.areaCode,
        //     _phoneWithAreaCodeEntity.phone,
        //     'forgot-password');
        return res;
      } catch (e) {
        await UtilsOther.showCustomShowError(e);
        // if (e is DioError) {
        //   customShowError(e.message);
        // } else {
        //   customShowError(S().network_error);
        // }
        return true;
      }
    }
    return false;
  }

  // Future<bool> getEmailCode() async {
  //   final form = _formKey.currentState;

  //   if (form != null) {
  //     form.save();

  //     if (!RegexUtil.isEmail(phoneController.text)) {
  //       customShowToast(S.of(context).enter_valid_email);
  //       return false;
  //       // }
  //     }
  //     bool isVertifica = await UtilsOther.checkShowVertification(
  //         account: phoneController.text, context: context);
  //     if (isVertifica == false) {
  //       return false;
  //     }

  //     try {
  //       bool res = await API.shared.login
  //           .getEmailCode(phoneController.text, 'forgot-password');
  //       return res;
  //     } catch (e) {
  //       await UtilsOther.showCustomShowError(e);
  //       // if (e is DioError) {
  //       //   customShowError(e.message);
  //       // } else {
  //       //   customShowError(S().network_error);
  //       // }
  //       return false;
  //     }
  //   }
  //   return false;
  // }

  Future _submit() async {
    final form = _formKey.currentState;
    // if (!_agree) {
    //   customShowToast(S.of(context).privacy_policy_consent_t);
    //   return;
    // }
    if (_canNext == false) {
      return;
    }

    if (form!.validate()) {
      form.save();
      // if (widget.type == 1) {
      //   if (!RegexUtil.isEmail(phoneController.text)) {
      //     customShowToast(S.of(context).enter_valid_email);
      //     return;
      //     // }
      //   } else {
      //     appContext.storage.setString('login_email', phoneController.text);
      //   }
      // } else {
      if (phoneController.text.length < 6 || phoneController.text.length > 60) {
        customShowToast(S.of(context).enter_valid_account);
        return false;
        // }
        // if (_phoneWithAreaCodeEntity.areaCode == '86') {
        //   if (!RegexUtil.isMobileSimple(_phoneWithAreaCodeEntity.phone)) {
        //     customShowToast(S.of(context).enter_valid_phone);
        //     return;
        //   }
        // } else if (!RegexUtil.matches(
        //     '^\\d{6,25}\$', _phoneWithAreaCodeEntity.phone)) {
        //   customShowToast(S.of(context).enter_valid_phone);
        //   return;
        // }
      }
      String type = '';
      try {
        type = await API.shared.login.postRegisterType(phoneController.text);
      } catch (e) {
        await UtilsOther.showCustomShowError(e);
        return ;
      }

      // if (type == '4' || type == '3') {
      //   customShowToast(S.of(context).login_unBind);
      //   return;
      // }

      if (type == '2') {
        try {
          bool res = await API.shared.login
              .emailVerifyCode("forgot-password", phoneController.text, _code);
          if (res) {
            appContext.storage.setString("login_account", phoneController.text);
            RouteManager.push(
              context,
              RoutMapping.forgetSetPasswordPage(1, _code),
            );
          } else {
            customShowError(S.current.login_IncorrectCode);
          }
        } catch (e) {
          await UtilsOther.showCustomShowError(e);
          // if (e is DioError) {
          //   customShowError(e.message);
          // } else {
          //   customShowError(S().network_error);
          // }
        }

        //       .phonePassword(code, mobileController.text, _password, _code);
      } else {
        // var code = '86';
        // String cachePhoneArea =
        //     appContext.storage.getString('login_area') ?? '';
        // if (cachePhoneArea != '') {
        //   code = cachePhoneArea;
        // }
        try {
          bool res = await API.shared.login
              .phoneVerifyCode("forgot-password", phoneController.text, _code);
          if (res) {
            appContext.storage.setString("login_account", phoneController.text);
            RouteManager.push(
              context,
              RoutMapping.forgetSetPasswordPage(0, _code),
            );
          } else {
            customShowError(S.current.login_IncorrectCode);
          }
        } catch (e) {
          await UtilsOther.showCustomShowError(e);
          // DLog(e.toString());
          // if (e is DioError) {
          //   customShowError(e.message);
          // } else {
          //   customShowError(S().network_error);
          // }
        }
      }
      // var code = '86';
      // String cachePhoneArea = appContext.storage.getString('login_area') ?? '';
      // if (cachePhoneArea != '') {
      //   code = cachePhoneArea;
      // }
      // try {
      //   await API.shared.login
      //       .phonePassword(code, mobileController.text, _password, _code);
      //   customShowSuccess(S.of(context).change_password_suss_login);
      //   Navigator.of(context).popUntil((route) => route.isFirst);
      // } catch (e) {
      //   if (e is DioError) {
      //     customShowError(e.message);
      //   } else {
      //     customShowError(S().network_error);
      //   }
      // }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          S.of(context).Forgot_password,
        ),
      ),
      body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: ClickUtils.debounce(() {
            // 触摸收起键盘
            FocusScope.of(context).requestFocus(FocusNode());
          }),
          child: Container(
              padding: EdgeInsets.only(left: 30.w, top: 30.w, right: 30.w),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    Row(
                      children: [
                        Text(
                          S.current.login_account_verify,
                          style: FontStyles.headerTextStyle_20
                              .copyWith(fontWeight: FontWeight.w600),
                        )
                      ],
                    ),
                    SizedBox(
                      height: 24,
                    ),
                    buildEmailView(),
                    // : LoginForgetPhoneFormField(
                    //     onChanged: (string) {
                    //       _phoneWithAreaCodeEntity.phone = string;
                    //       checkInputCanNext();
                    //     },
                    //     focusNode: phoneFocusNode,
                    //     onSaved: (val) {
                    //       if (val != null) {
                    //         _phoneWithAreaCodeEntity = val;
                    //       }
                    //     },
                    //   ),
                    Container(
                      color: Colors.black.withOpacity(0.2),
                      height: 0.5,
                    ),
                    Container(
                        margin: EdgeInsets.only(top: 20),
                        height: 50,
                        child: CodeFormField(
                          tagStr: 'forgetPasswordPage',
                          suffixColor: Colors.black.withOpacity(0.8),
                          // color: Colors.black.withOpacity(0.8),
                          getSmsCode: getSmsCode,
                          // widget.type == 1 ? getEmailCode : getSmsCode,
                          focusNode: codeFocusNode,
                          onChanged: (string) {
                            _code = string;
                            checkInputCanNext();
                          },
                          decoration: LoginForgetInputDecoration(horizontal: 0),
                          onSaved: (val) {
                            print(val);
                            if (val != null) {
                              _code = val;
                            }
                          },
                        )),
                    Container(
                      color: Colors.black.withOpacity(0.2),
                      height: 0.5,
                    ),
                    GestureDetector(
                      child: Container(
                        height: 48,
                        alignment: Alignment.center,
                        margin: EdgeInsets.only(top: 60.w),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            color: _canNext
                                ? ThemeColor.primaryColor
                                : ThemeColor.primaryColor.withOpacity(0.2)),
                        child: Text(
                          S.current.continues,
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            color: _canNext
                                ? Colors.black
                                : Colors.black.withOpacity(0.4),
                          ),
                        ),
                      ),
                      onTap: ClickUtils.debounce(() {
                        _submit();
                      }),
                    )
                  ],
                ),
              ))),
    );
  }

  Widget buildEmailView() {
    return TextField(
      enableInteractiveSelection: false,
      focusNode: phoneFocusNode,
      controller: phoneController,
      inputFormatters: [
        FilteringTextInputFormatter.deny(appContext.emojiRegexp)
      ],
      maxLength: 60,
      onChanged: (value) {
        checkInputCanNext();
      },
      onSubmitted: (value) {
        codeFocusNode.requestFocus();
      },
      style: TextStyle(
        fontSize: 16,
        color: Colors.black.withOpacity(0.8),
      ),
      cursorColor: ThemeColor.primaryColor,
      decoration: InputDecoration(
          counterText: '',
          contentPadding: EdgeInsets.symmetric(vertical: 0),
          border: OutlineInputBorder(borderSide: BorderSide.none),
          hintText: S.current.enter_account,
          hintStyle:
              TextStyle(fontSize: 16, color: Colors.black.withOpacity(0.4))),
    );
  }

  checkInputCanNext() {
    if (phoneController.text.length >= 6 &&
        phoneController.text.length <= 60 &&
        _code.length == 6) {
      if (mounted) {
        setState(() {
          _canNext = true;
        });
      }
    } else {
      if (mounted) {
        setState(() {
          _canNext = false;
        });
      }
    }
    // if (widget.type == 1) {
    //   if (RegexUtil.isEmail(phoneController.text) && _code.length == 6) {
    //     if (mounted) {
    //       setState(() {
    //         _canNext = true;
    //       });
    //     }
    //   } else {
    //     if (mounted) {
    //       setState(() {
    //         _canNext = false;
    //       });
    //     }
    //   }
    // } else {
    //   if (_phoneWithAreaCodeEntity.areaCode == '86' &&
    //       _code.length == 6 &&
    //       RegexUtil.isMobileSimple(_phoneWithAreaCodeEntity.phone)) {
    //     if (mounted) {
    //       setState(() {
    //         _canNext = true;
    //       });
    //     }
    //     // }
    //   } else if (_phoneWithAreaCodeEntity.areaCode != '86' &&
    //       RegexUtil.matches('^\\d{6,25}\$', _phoneWithAreaCodeEntity.phone) &&
    //       _code.length == 6) {
    //     // _canNext = true;
    //     if (mounted) {
    //       setState(() {
    //         _canNext = true;
    //       });
    //     }
    //   } else {
    //     _canNext = false;
    //     if (mounted) {
    //       setState(() {
    //         _canNext = false;
    //       });
    //     }
    //   }
    // }
  }

  @override
  void initState() {
    super.initState();
// KeyboardVisibilityController().onChange.listen
    KeyboardVisibilityController().onChange.listen((bool visible) {
      print('Keyboard visibility update. Is visible: $visible');
      if (visible == false) {
        _formKey.currentState?.save();
        checkInputCanNext();
      }
    });
    // if (widget.type == 1) {
    String cacheEmail = appContext.storage.getString("login_account") ?? '';
    if (cacheEmail.isNotEmpty) {
      phoneController.text = cacheEmail;
    }
    // }
    // phoneFocusNode.addListener(() {
    //   setState(() {
    //     blurBackground = phoneFocusNode.hasFocus;
    //   });
    // });
    // pwdFocusNode.addListener(() {
    //   setState(() {
    //     blurBackground = pwdFocusNode.hasFocus;
    //   });
    // });
  }
}
